package wymiana.utils;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploader {

	@SuppressWarnings("unchecked")
	public byte[] getFileContent(HttpServletRequest request)
			throws FileUploadException {
		if (!ServletFileUpload.isMultipartContent(request)) {
			throw new RuntimeException();
		}
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(request);
		return items.get(0).get();
	}

	public void respond(HttpServletResponse response, String message)
			throws IOException {
		response.getOutputStream().write(message.getBytes());
	}
	/*
	 * public void getExportedConfiguration( HttpServletRequest request) throws
	 * FileUploadException { String xml; try { xml = getFileContent(request,
	 * Charset.forName("UTF-8")); } catch (FileUploadException fuex) { throw new
	 * FileUploadException("Cannot upload the file: " + fuex.getMessage()); }
	 * try { } catch (StreamException ex) { throw new
	 * FileUploadException("Invalid XML file format", ex); } catch (Exception
	 * ex) { throw new FileUploadException(
	 * "Unable to transform XML to configuration", ex); } }
	 */

	/*
	 * public ExportedTRN getExportedTRN(HttpServletRequest request) throws
	 * FileUploadException { String xml; try { xml = getFileContent(request,
	 * Charset.forName("UTF-8")); } catch (FileUploadException fuex) { throw new
	 * FileUploadException("Cannot upload the file: " + fuex.getMessage()); }
	 * try { return ExportedTRN.doImport(xml); } catch (StreamException ex) {
	 * throw new FileUploadException("Invalid XML file format", ex); } catch
	 * (Exception ex) { throw new FileUploadException(
	 * "Unable to transform XML to TRN", ex); } }
	 * 
	 * public List<TRNItem> getTRNFromTxt(HttpServletRequest request) throws
	 * FileUploadException, IOException{ String trn; try {
	 * trn=getFileContent(request,Charset.forName("UTF-8")); }
	 * catch(FileUploadException fuex){ throw new
	 * FileUploadException("Cannot upload file"); } try { // return
	 * TRNParser.parse(trn); } catch (StreamException ex) { throw new
	 * FileUploadException("Invalid TXT file format", ex); } return null; }
	 */

}